<script lang="ts">
import {defineComponent, type PropType, reactive, ref, toRefs} from 'vue'
import {Group, SaveFormConfig} from "@/components/saveForm/types/type.ts";
import {axiosHttp} from "@/util/axios.ts";
import {CompUserError} from "@/common/comTypes/errorType.ts";

export default defineComponent({
  name: 'saveForm',
  props: {
    saveFormConfigList: {
      type: Array<SaveFormConfig>,
      default: () => []
    },
    saveForm: {
      type: Object,
      default: () => {
      }
    },
    width: {
      type: String,
      default: '66%'
    },
    customerInit: {
      type: Function,
      default: () => {
      },
    },
    autoSearch: {
      type: Boolean,
      default: true,
    },
    detailUrl: {
      type: String,
      default: ""
    },
    saveUrl: {
      type: String,
      default: ""
    },
    customSave: {
      type: Function,
      default: () => {
      }
    },
    autoSave: {
      type: Boolean,
      default: true
    },
    rules: {
      type: Object,
      default: () => {
      }
    },
    title: {
      type: String,
      default: "新增"
    },
    currentGroup: {
      type: String as PropType<Group>,
      default: 'add'
    }

  },
  emits: ['beforeClose', 'submit', 'saveSuccess', 'updateForm'],
  setup(props, {emit}) {

    const data = reactive({
      showDialog: false,
      showLoading: false,
    })

    const methods = {
      init(id: string) {
        data.showDialog = true
        data.showLoading = true
        if (id) {
          if (props.autoSearch) {
            if (!props.detailUrl) {
              throw new CompUserError("组件使用错误:开启自动查询必须填写查询地址")
            }
            methods.detail(id)
          } else {
            props.customerInit()
          }
        }

        data.showLoading = false
      },

      beforeClose() {
        data.showDialog = false
        emit("beforeClose")
      },
      async detail(id: string) {
        const res = await axiosHttp.get(props.detailUrl.endsWith("/") ? (props.detailUrl + id) : (props.detailUrl + "/" + id))
        if (res.isSuccess()) {
          emit("updateForm", res.data)
        }
      },
      submit() {
        if (props.autoSave) {
          if (!props.saveUrl) {
            throw new CompUserError("组件使用错误:开启自动保存必须填写保存地址")
          }
          refs.formRef.value.validate(async (flag: boolean) => {
            if (flag) {
              if (props.autoSave) {
                data.showLoading = true
                await axiosHttp.post(props.saveUrl, props.saveForm)
                data.showLoading = false
              } else {
                await props.customSave()
              }
              //请求成功后的操作
              emit("saveSuccess")
              //关闭弹窗
              methods.beforeClose()
            }
          })
        } else {
          emit("submit", props.saveForm)
          //关闭弹窗
          methods.beforeClose()
        }

      },
      clearRulesAsync(time: number = 50) {
        setTimeout(() => {
          refs.formRef.value.clearValidate()
        }, time)

      }

    }

    const validators = {}

    const refs = {
      formRef: ref()
    }


    return {
      ...toRefs(data),
      ...methods,
      ...refs,
      ...validators,

    }
  }
})
</script>

<template>

  <el-dialog :model-value="showDialog" :title="title" :width="width" :before-close="beforeClose">
    <el-form ref="formRef" :model="saveForm" v-loading="showLoading" :rules="rules" label-position="left">
      <el-row v-for="(item,index) in saveFormConfigList">
        <el-form-item
            v-if="item.group.includes(currentGroup)||currentGroup=='update'"
            :key="item?.prop"
            :label="item?.label"
            label-width="85px"
            :style="{width:item?.width}"
            :prop="item?.prop"
        >

          <el-input
              style="width: 100%"
              v-if="!item.customSlotName"
              :disabled="currentGroup=='detail'||(currentGroup=='update'&&!item.group.includes('update'))"
              v-model="saveForm[item?.prop||'-']"
              :title="(currentGroup=='detail'||(currentGroup=='update'&&!item.group.includes('update')))?item?.title:''"
              :placeholder="item.placeholder? item.placeholder :'请输入'+item.label"
          >

          </el-input>

          <slot v-else :name="item?.customSlotName">
          </slot>
        </el-form-item>
      </el-row>


      <slot name="buttonSlot">
        <el-form-item v-if="currentGroup!='detail'">
          <el-row class="flex-center gap-x-10 " style="width: 100%">
            <el-button type="text" @click="submit">提交</el-button>
            <el-button type="text" @click="beforeClose">取消</el-button>
          </el-row>
        </el-form-item>
      </slot>

    </el-form>
  </el-dialog>
</template>

<style scoped>

</style>